
package com.wasu.sdk_ott.utils;

import static android.content.Context.CONNECTIVITY_SERVICE;
import static com.wasu.constant.HttpDomainKt.TAG;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.wasu.UILApplication;
import com.wasu.constant.Config;
import com.wasu.dynamicload.internal.DLPluginManager;
import com.wasu.hostlib.internal.DLPluginPackage;

import org.json.JSONObject;
import org.ngb.system.DataAccess;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * @author liqiuxu
 */
public class WasuTvModelUtil {

    /**
     * 本手机型号
     */
    public static final String UNKNOWN = "unknown";

    /**
     * true为IP mode,false 为 4K cable Mode
     */
    public static boolean bIpMode = false;

    public static boolean isbIpMode() {
        return bIpMode;
    }
    public static void setbIpMode(boolean bIpMode) {
        Log.d(TAG, "setbIpMode = " + bIpMode);
        WasuTvModelUtil.bIpMode = bIpMode;
    }

    private static String stdId = null;

    public static final String model_wasu_value = getSystemOsString("ro.wasu.product.model");

    /**
     * 中间件类型
     * evm 01 表示英立视 ipanel 02 表示茁壮
     */
    public static String model_wasu_mwType = null;

    public static final String stdid_wasu_value = getSystemOsString("ro.wasu.product.stbid");//Defaults.VirtualTVID

    public static String ro_wasu_sw_version = null;//getSystemOsVersion_zhuozhuang();

    public static String ro_wasu_hw_version = null;//getSystemOsHardVersion_zhuozhuang();

    private static String getSystemOsString(String property) {
        Class<?> clazz = null;
        try {
            clazz = Class.forName("android.os.SystemProperties");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return UNKNOWN;
        }
        Method met = MethodUtils.getMatchingAccessibleMethod(clazz,
                "get", new Class[]{String.class, String.class});
        Object obj = null;
        try {
            obj = met.invoke(null, new Object[]{property, UNKNOWN});
        } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            return UNKNOWN;
        }
        return (String) obj;
    }

    /**
     * 获取默认的UserProfile
     * @return
     */
    public static String getDefaultUserProfile(){
        if(model_wasu_value.startsWith("WASU_4K_TVOS")){//省网
            return "03#999999999#999999#1-100##";
        }else if(model_wasu_value.startsWith("WASU_4K")){//杭网
            return "01#999999999#999999#1-571##";
        } else{
            return "";
        }
    }

    public static synchronized String getSystemOsVersion_zhuozhuang() {
        if (ro_wasu_sw_version == null) {
            ro_wasu_sw_version = getSystemOsString("ro.wasu.sw_version");
        }
        return ro_wasu_sw_version;
    }

    public static synchronized String getSystemOsHardVersion_zhuozhuang() {

        if (ro_wasu_hw_version == null) {
            ro_wasu_hw_version = getSystemOsString("ro.wasu.hw_version");
        }
        return ro_wasu_hw_version;
    }

    public static synchronized String getSystemOsMiddleWare(){
        if (TextUtils.isEmpty(model_wasu_mwType)){
            model_wasu_mwType = getSystemOsString("ro.wasu.mw_type");
        }
        return model_wasu_mwType;
    }

    public synchronized static String wasu_bsa_getTvid() {
        if(Config.customedStdId != null){
            return Config.customedStdId;
        }
        if (stdId == null) {
            if (!WasuTvModelUtil.stdid_wasu_value.equals(WasuTvModelUtil.UNKNOWN)) {
                stdId = WasuTvModelUtil.stdid_wasu_value;
            } else {
                stdId = WasuTvModelUtil.UNKNOWN;//"111800609120F0C24CD1A3FF";//"111800809120F0C24CD21050";//111800809120F0C24CD21050  1104002091800024C126B8F6
            }
        }
        return stdId;
    }


    public static String[] getInfo(Context ctx, String... projection) {
        if(projection==null || ctx == null){
            return new String[0];
        }
        SharedPreferences sp = ctx.getSharedPreferences(Config.PREFERENCE_NAME, Context.MODE_PRIVATE);
        String[] result = new String[projection.length];
        for (int i = 0; i < projection.length; i++) {
            if ("User-Agent".equals(projection[i])) {
                result[i] = getWasuUserAgent(ctx);
            } else {
                result[i] = sp.getString(projection[i], "");
            }
        }
        return result;
    }

    public static String getWasuUserAgent(Context context) {
        if(context == null){
            return null;
        }
        PackageInfo packageInfo;
        //todo LC 这里取插件版本号，待确认
      /*  String bodyver = getPluginVersionName(context, "com.wasu.plugin.body");
        String sdkver =getPluginVersionName(context, "com.wasu.plugin.sdk");*/
        String bodyver = "99.99.P-2501151426";
        String sdkver = "99.99.P-2501151431";
        try {
            packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            throw new IllegalStateException("getPackageInfo failed");
        }

        return "Wasu/1.0 (" + String.format("%s:%s; %s:%s; %s:%s; %s:%s; %s:%s; %s:%s; %s:%s; %s:%s",
                "mwver",
                WasuTvModelUtil.getSystemOsVersion_zhuozhuang(),//Build.VERSION.RELEASE, by wangjian IPLoader need system version
                "hwver",
                WasuTvModelUtil.getSystemOsHardVersion_zhuozhuang(),
                "swver",
                packageInfo.versionName,
                "uiver",
                "1.0",
                "caver",
                "unkown",
                "sdkint",
                Build.VERSION.SDK_INT,
                "bodyver",
                !TextUtils.isEmpty(bodyver)?bodyver:"0",
                "sdkver",
                !TextUtils.isEmpty(sdkver)?sdkver:"0") +")";
    }


    public static String getPluginVersionName(Context context, String pluginName){
        if(TextUtils.isEmpty(pluginName)){
            return "0";
        }
        String pluginVersionName;
        try {
            DLPluginManager pluginManager = DLPluginManager.getInstance(context);
            if (pluginManager == null){
                Log.e(TAG, "getPluginVersionName, pluginManager can not be null");
                return "0";
            }
            DLPluginPackage pluginPackage = pluginManager.peekPackage(pluginName);
            if (pluginPackage == null){
                Log.e(TAG, "getPluginVersionName, pluginPackage can not be null");
                return "0";
            }
            PackageInfo packageInfo = pluginPackage.packageInfo;
            if (packageInfo == null){
                Log.e(TAG, "getPluginVersionName, packageInfo can not be null");
                return "0";
            }
            pluginVersionName = packageInfo.versionName;
        }catch (Exception e){
            e.printStackTrace();
            pluginVersionName = "0";
        }
        return pluginVersionName;
    }

    /**
     * 生成随机数UUID
     * @return 32 uuid
     */
    public static String getUUID(){
        UUID uuid= UUID.randomUUID();
        return uuid.toString().replace("-", "");
    }

    /**
     * MD5加密
     * @param source 源
     * @return md5值
     */
    public static String md5(byte[] source) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] bytes = digest.digest(source);
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xFF);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result.append(temp);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取测试的URL
     * @param key 各个系统的Key
     * @return 测试url
     */
    public static String getDebugDoamin(String key){
        SharedPreferences sp = UILApplication.getInstance().getApplication().getApplicationContext().getSharedPreferences(Config.PREFERENCE_DOMAIN_DEBUG, Context.MODE_MULTI_PROCESS);
        return sp.getString(key, "");
    }
    public static boolean checkNetworkConnected() {
        boolean isConnect = false;
        ConnectivityManager connectMgr = (ConnectivityManager) UILApplication.getInstance().getApplication().getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo ethNetworkInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
        if (ethNetworkInfo != null && ethNetworkInfo.isConnected()) {
            Log.e("UILApplication", "bootupgetcookie: ethNetworkInfo=true");
            isConnect = true;
        }
        NetworkInfo wifiNetworkInfo = connectMgr
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifiNetworkInfo != null && wifiNetworkInfo.isConnected()) {
            Log.e("UILApplication", "bootupgetcookie: wifiNetworkInfo=true");
            isConnect = true;
        }
        NetworkInfo networkInfo = connectMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            Log.e("UILApplication", "bootupgetcookie: networkInfo=true");
            isConnect = true;
        }
        return isConnect;
    }

    /**
     * 获取liveType
     * @return liveType
     */
    public static int getLiveType(){
        int type =-1;
        //通过反射调用
        try {
            String value = DataAccess.getInstance().getProperty("LiveType");
            Log.i(TAG, "getLiveType, value = "+value);
            if (!TextUtils.isEmpty(value)){
                JSONObject valueObject = new JSONObject(value);
                type = valueObject.getInt("LiveType");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return type;
    }

}
